package com.applink.sell_proof.urlimageviewhelper;

import android.content.Context;
import android.graphics.PointF;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class GalleryClaimViewPager extends ViewPager {

	private PointF mLast;

	public RotateImageView mCurrentView;

	public GalleryClaimViewPager(Context context) {
		super(context);
	}

	public GalleryClaimViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) {
			super.onTouchEvent(event);
		}

		if (mCurrentView == null)
			return false;

		float[] difference = handleMotionEvent(event);

		if (mCurrentView.pagerCanScroll()) {
			return super.onTouchEvent(event);
		} 
		else {
			if (difference != null && mCurrentView.onRightSide
					&& difference[0] < 0) // move right
			{
				return super.onTouchEvent(event);
			}
			if (difference != null && mCurrentView.onLeftSide
					&& difference[0] > 0) // move left
			{
				return super.onTouchEvent(event);
			}
			if (difference == null
					&& (mCurrentView.onLeftSide || mCurrentView.onRightSide)) {
				return super.onTouchEvent(event);
			}
		}

		return false;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent event) {

		if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) {
			super.onInterceptTouchEvent(event);
		}

		if (mCurrentView == null)
			return false;

		float[] difference = handleMotionEvent(event);

		if (mCurrentView.pagerCanScroll()) {
			return super.onInterceptTouchEvent(event);
		} 
		else {
			if (difference != null && mCurrentView.onRightSide
					&& difference[0] < 0) // move right
			{
				return super.onInterceptTouchEvent(event);
			}
			if (difference != null && mCurrentView.onLeftSide
					&& difference[0] > 0) // move left
			{
				return super.onInterceptTouchEvent(event);
			}
			if (difference == null
					&& (mCurrentView.onLeftSide || mCurrentView.onRightSide)) {
				return super.onInterceptTouchEvent(event);
			}
		}
		return false;
	}

	public void Zoom(boolean zoom) {
		mCurrentView.onZoom(zoom);
	}

//	public void Rotate(boolean rotate) {
//		mCurrentView.onRotate(rotate);
//	}

	/**
	 * small motion between finger down and up
	 * 
	 * @param event
	 * @return
	 */
	private float[] handleMotionEvent(MotionEvent event) {
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			mLast = new PointF(event.getX(0), event.getY(0));
			break;
		case MotionEvent.ACTION_MOVE:
		case MotionEvent.ACTION_UP:
			PointF curr = new PointF(event.getX(0), event.getY(0));
			return new float[] { curr.x - mLast.x, curr.y - mLast.y };

		}
		return null;
	}
}